package com.dataStructure.Stack;

/**
 * @author roger
 *
 *stack:符合先进后出的原则，基本操作包括：（基于数组，无法扩展,存放内容为object对象）
 *1、创建一个stack
 *2、检查是否为空
 *3、push：增加元素
 *4、top：获得栈顶元素
 *5、pop：删除栈顶元素
 *
 */
public class MyStack {
	int maxSize;
	Object[] data;
	int top;
	final int initTopValue = -1;
	
	
	/**初始化栈，top为-1，大小固定，无法扩张
	 * @param maxSize
	 */
	public MyStack(int maxSize){
		this.maxSize = maxSize;
		this.data = new Object[this.maxSize];
		this.top = initTopValue; 
	}
	
	public boolean isEmpty() {
		return this.top == initTopValue?true:false;
	}
	
	/**
	 * 向栈中加入数据
	 */
	public void push(Object object) {
		if (top >= maxSize-1) {
			System.out.println("stack is full");
		}
		else {
			this.top++;
			this.data[this.top] = object;
			System.out.println("push success: "+object);
		}
	}
	
	/**获取栈顶元素
	 * @return
	 */
	public Object top() {
		Object result = null;
		if (!this.isEmpty()) {
			result = this.data[this.top];
		}else {
			System.out.println("stack is empty");
		}
		return result;
	}
	
	/**
	 * 删除栈顶元素
	 */
	public void pop() {
		if (top!=initTopValue) { //不是初始值
			data[top] = null;
			top--;
			System.out.println("stack pop success");
		}else {
			System.out.println("stack is already empty");
		}
	}
	
	/**
	 * 测试类
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyStack myStack  = new MyStack(20);
		
		System.out.println(myStack.isEmpty());
		for (int i = 0; i < 23; i++) {
			myStack.push(new String("test"+i));
		}
		
		System.out.println(myStack.isEmpty());
		
		for (int i = 0; i < 25; i++) {
			System.out.println(myStack.top());
			myStack.pop();
		}
	}
	
}
